﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Chat.Server
{
    /// <summary>
    /// Implementation of the WelcomeClient abstract class, which uses
    /// the TCP communication.
    /// </summary>
    public class WelcomeTcpClient : WelcomeClient
    {
        /// <summary>
        /// The IP end point to listen of for incomming tcp clients.
        /// </summary>
        protected IPEndPoint ListenOn { get; set; }
        protected TcpListener Listener { get; set; }

        public WelcomeTcpClient(IPEndPoint listenOn)
        {
            ListenOn = listenOn;

            Listener = new TcpListener(ListenOn);
        }
        
        /// <summary>
        /// Since we use the TCP communication, the TcpConnection(ServerCmd)
        /// implementation of the Connection abstract class will be returned
        /// as the communication channel with the newly connected client.
        /// </summary>
        /// <returns>
        /// The instanse of the TcpConnection(ServerCmd) class, which will
        /// represent the communication channel with the newly connected client.
        /// </returns>
        protected override Connection<ServerCmd> AcceptClient()
        {
            try
            {
                TcpClient client = Listener.AcceptTcpClient();
                return new TcpConnection<ServerCmd>(client);
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// Will start the .NET TcpListener.
        /// </summary>
        protected override void Open()
        {
            Listener.Start();
        }

        /// <summary>
        /// Will stop the .NET TcpListener.
        /// </summary>
        protected override void Close()
        {
            Listener.Stop();
        }
    }
}
